import mongoose from 'mongoose';
import moment from 'moment';
import db from './db';
mongoose.Promise = global.Promise;

const PostSchema = new mongoose.Schema({
    title: String, // 如果是课程就是老师
    content: String, // 内容；如果是课程就是老师
    college: String, // 学院（针对课程）
    votes: String,
    imgs: Array, // 附件图片
    category: String, // 所属分类
    secCategory: {type: String, default: ''}, // 二级分类
    createTime: Number,
    startTime: Number,
    endTime: Number,
    creatorId: String,
    creator: Object,
    type: Number, // 0 post, 1 activity, 2 vote, 3. 课程, 4. 二手
    activityObj: Object, // {fee, num, place}
    voteObj: Object, // {isMulti, list}
    scObj: Object, // {isBuy, price}
    courseObj: Object, // {gender, college}
    isAuth: Boolean,
    likeNum: {type: Number, default: 0},
    shareNum: {type: Number, default: 0},
    cmtNum: {type: Number, default: 0},
    viewNum: {type: Number, default: 0},
    joinNum: {type: Number, default: 0},
    isTop: Boolean,
    schoolId: String, // 所属学校
    tags: Object, //课程标签
    scores: Array, //课程分数
    isDeleted: {type: Boolean, default: false},
});

PostSchema.methods.savePost = function (post, cb) {
    post.createTime = moment().unix();
    this.model('post').insertMany([post], cb);
};

PostSchema.methods.getPosts = function (query, cb) {
    const { current = 1, pageSize = 10, ...leftQuery } = query;
    const postModel = this.model('post');
    if (leftQuery.createTime) {
        leftQuery.createTime = { $lt: leftQuery.createTime };
    }
    if (!leftQuery.isDeleted) {
        leftQuery.isDeleted = { $ne: true };;
    }
    postModel.count(leftQuery, function (err, count) {
        const hasMore = count / pageSize > current;
        postModel.find(leftQuery).sort({createTime: -1}).skip((current - 1) * pageSize).limit(pageSize).exec((err, posts) => cb(err, posts, count, hasMore));
    });
};

PostSchema.methods.getBest10Posts = function (query, cb) {
    const postModel = this.model('post');
    postModel.find(query).sort({likeNum: -1, cmtNum: -1}).limit(10).exec((err, posts) => cb(err, posts));
};


PostSchema.methods.getAllPosts = function (query, cb) {
    this.model('post').find(query, { name: 1, _id: 0 }, cb);
};

PostSchema.methods.getPost = function (query, cb) {
    this.model('post').findOne(query, cb);
};

PostSchema.methods.updatePost = function (post, cb) {
    const _id = post._id;
    delete post._id;
    this.model('post').findOneAndUpdate({ _id }, { $set: post }, cb);
};

PostSchema.methods.removePosts = function (postIds, cb) {
    this.model('post').remove({ _id: { $in: postIds } }, cb);
};

export default db.model('post', PostSchema);